<template>
  <div class="role-assign-user">
    <SelfAdaption onSearch="1">
      <!-- 左侧插槽 -->
      <template slot="adaption-left">
        <div class="slot-item">
          <RPButton optType="common" :text="$t('module.userManage.assigningUsers')" @click="assignUser" />
        </div>
        <div class="slot-item">
          <RPButton optType="batch" @click="deleted()" />
        </div>
      </template>

      <!-- 右侧插槽 -->
      <template slot="adaption-right">
        <div class="slot-item">
          <Input
            v-model="nameOrAccount"
            :placeholder="$t('module.userManage.searchUsers')"
            class="input-search"
            icon="ios-search"
            small
            @on-enter="onSearch"
            @on-click="onSearch"
          />
        </div>
      </template>
    </SelfAdaption>
    <InnerPageTable ref="userTable" :config="tableConfig"></InnerPageTable>
  </div>
</template>
<script>
import { roleAssignUserColumns } from './columns.js'
import locales from './locales.js'
import orgAssignRoleAPI from '@/api/orgAssignRoleAPI.js'
import RoleSelectUser from './RoleSelectUser.vue'
import appAssignUserAPI from '@/api/appAssignUserAPI.js'
import { queryOrgsByOrgPaths, getLowcodeDataSyncEnable } from '@/api/orgApi'
import softwareLicence from './softwareLicence.vue'

export default {
  name: 'role-assign-user',
  mixins: [locales],
  props: {
    topNode: {
      type: Boolean,
      default() {
        return false
      }
    },
    category: {
      type: Number,
      default() {
        return 0
      }
    },
    roleCode: {
      type: Object,
      default() {
        return {}
      }
    },
    tenantCode: {
      type: String,
      default() {
        return ''
      }
    },
    orgId: {
      type: String,
      default() {
        return ''
      }
    },
    roleId: {
      type: String,
      default() {
        return ''
      }
    },
    orgRoleId: {
      type: String,
      default() {
        return ''
      }
    },
    roleCode: {
      type: String,
      default() {
        return ''
      }
    },
    orgName: String,
    roleName: String
  },
  data() {
    return {
      tableData: [],
      showSoftwareLicence: false,
      nameOrAccount: ''
    }
  },
  watch: {},
  computed: {
    tableConfig() {
      return {
        columnsFn: roleAssignUserColumns.bind(this),
        // columnsFn: this.roleAssignUserColumns,
        loadDataFn: this.loadAssignedUsers,
        // resource: this.tableData,
        // isPage: true,
        autoFirst: true,
        initParam: {
          orgId: this.orgId,
          roleId: this.roleId,
          roleName: this.roleName,
          nameOrAccount: this.nameOrAccount
        },
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    }
  },
  created: function() {
    getLowcodeDataSyncEnable().then(res => {
      this.showSoftwareLicence = res.data
    })
  },
  mounted() {
    // this.search();
  },
  methods: {
    // 自定义行样式
    rowClassName(row) {
      // locked:有效：0；无效：1
      if (row.locked == 1) {
        return 'tableDisableStyle'
      }
    },
    search() {
      this.$refs['userTable'].load({ nameOrAccount: this.nameOrAccount })
    },
    async loadAssignedUsers({ responseProcess, param }) {
      await orgAssignRoleAPI.getAssignedUser(param).then(data => {
        data.currentPage = data.pageNum
        delete data.pageNum
        data.recordCount = data.total
        delete data.total
        let records = data.records
        // 后台返回数据可能会是 [null, null, null, null, null]
        if (records.length > 0 && records[0] != null) {
          let orgPaths = records.map(user => {
            return user.orgPath
          })
          queryOrgsByOrgPaths(orgPaths).then(orgs => {
            records.forEach(user => {
              let userOrg = orgs.find(org => {
                return org.orgPath == user.orgPath
              })
              user._hasOrgInfo = true
              if (userOrg) {
                user.orgName = userOrg.orgName
                user.orgNameFullPath = userOrg.orgNameFullPath
              } else {
                user.orgName = user.orgPath
                user.orgNameFullPath = user.orgPath
              }
              // 1.组织树顶级节点 2.平台管理员登录  3.默认分配的平台管理员角色  4.默认分配的平台管理员账号   不可删除用户
              if (this.topNode && this.category == '1' && this.roleCode == 'admin-dadp' && user.userId == 'admin') {
                user._disabled = true
              }
            })
            responseProcess(data)
          })
        }
        data.recordList = data.records
        delete data.records
        // this.tableData = data;
        // if(param.roleName == '开发者') {
        //   getLowcodeDataSyncEnable().then(res => {
        //     this.showSoftwareLicence = res.data
        //   })
        // }
        responseProcess(data)
      })
    },
    assignUser() {
      new this.$pageModal(
        RoleSelectUser,
        {
          props: {
            tenantCode: this.tenantCode,
            orgId: this.orgId,
            roleId: this.roleId,
            orgRoleId: this.orgRoleId,
            roleCode: this.roleCode,
            orgName: this.orgName,
            roleName: this.roleName
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    deleted() {
      let { relIds: selectedIds, ids } = this.getSelectedIds()
      if (selectedIds.length == 0) {
        this.$message.error(this.$t('module.role.warning.selectUsers'))
        return
      }
      // 删除提示级别：普通
      new $confirm(this.$t('module.role.warning.confirmDeleteAssignedUser'), this).then(() => {
        let param = {
          orgId: this.orgId,
          roleId: selectedIds
        }
        orgAssignRoleAPI.deleteAssignedUser(selectedIds).then(res => {
          // this.deleteAppAssignedUser(ids);需求变更，该逻辑改到后端处理。
          this.$message.success({
            content: this.$t('module.orgManage.deleteSuccess'),
            duration: 3
          })
          this.search()
        })
      })
    },
    getSelectedIds() {
      let list = this.$refs['userTable'].getSelectioned() || []
      let relIds = []
      let ids = []
      for (let { orgRoleUserRelId, id } of list) {
        relIds.push(orgRoleUserRelId)
        ids.push(id)
      }
      return { relIds, ids }
    },
    onSearch() {
      this.search()
    },
    deleteAppAssignedUser(selectedIds) {
      // 从预置角色中删除用户时，删除应用与用户的关联
      if ((this.roleCode == 'admin-dadp' || this.roleCode == 'admin-tenant') && selectedIds.length > 0) {
        let param = {
          userApplicationInfoVo: {
            applicationCode: 'RIPPLES.crc',
            applicationType: 0,
            topic: ''
          },
          userIds: selectedIds
        }
        appAssignUserAPI.deleteAssignedUser(param)
      }
    },
    goLicence(val) {
      // console.log(val.row)
      new this.$pageModal(
        softwareLicence,
        {
          props: {
            userId: val.row.userId,
            roleCode: val.row.roleCode,
            userName: val.row.userName,
            id: val.row.id
          }
        },
        data => {}
      )
    }
  },
  directives: {}
}
</script>
<style lang="less">
.role-assign-user {
  height: 100%;
  background-color: white;

  .input-search {
    z-index: 99;
    float: right;
    width: 200px;

    input {
      color: #515a6e;
    }
  }

  .ivu-table-wrapper {
    z-index: 99;
  }

  .ivu-select-selection {
    z-index: 99;
  }

  .self-adaption-wrap {
    padding: 10px 5px 0;
  }

  .table-bar {
    display: none;
  }

  .single-table-con {
    padding: 0 10px 5px;
  }

  .ivu-spin {
    text-align: left;
  }

  .spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
}
</style>
